<script setup>
import { ref, getCurrentInstance, onMounted, reactive, nextTick } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'

const { proxy } = getCurrentInstance()
const tableData = ref([])
const formInline = reactive({
  keyword: ''
})   // 搜索输入框数据
// getUserData请求的参数
const config = reactive({
  name: '',
  total: 0,
  page: 1
})
// 判断对话框是新增还是编辑状态
const action = ref('add')
// 对话框是否开启
const dialogVisible = ref(false)
// 对话框的数据
const formUser = reactive({})
// 对话框表单校验规则
const rules = reactive({
  name: [{ required: true, message: '姓名是必填项', trigger: 'blur' }],
  age: [
    { required: true, message: '年龄是必填项', trigger: 'blur' },
    { type: 'number', message: '年龄必须是数字' },
  ],
  sex: [{ required: true, message: '性别是必选项', trigger: 'change' }],
  birth: [{ required: true, message: '出生日期是必选项' }],
  addr:[{ required: true, message: '地址是必填项' }]
})

const getUserData = async () => {
  const data = await proxy.$api.getUserData(config)
  console.log(data)
  tableData.value = data.list.map(item => ({
    ...item,
    sex: Number(item.sex) === 1 ? '男' : '女'
  }))
  config.total = data.count
}
const tableLabel = reactive([
  { prop: 'name', label: '姓名' },
  { prop: 'age', label: '年龄' },
  { prop: 'sex', label: '性别' },
  { prop: 'birth', label: '出生日期', width: 200 },
  { prop: 'addr', label: '地址', width: 400 },
])

// 点击搜索按钮或搜索框回车
const handleSearch = () => {
  config.name = formInline.keyword
  getUserData()
}

// 分页改变页面
const handleChange = page => {
  config.page = page
  getUserData()
}

// 删除功能
const handleDelete = (row) => {
  // console.log(row)
  ElMessageBox.confirm('你确定要删除吗？').then(async() => {
    await proxy.$api.deleteUser({id: row.id})
    ElMessage({
      showClose: true,
      message: '删除成功',
      type: 'success'
    })
    getUserData()
  })
}


// user页面表格数据编辑按钮点击事件
const handleEdit = (row) => {
  action.value = 'edit'
  dialogVisible.value = true
  // 这里用nextTick的原因是：DOM是异步更新的，如果不等DOM更新完才复制数据，会导致初始值改变
  nextTick(() => {
    Object.assign(formUser, {...row, sex: String(row.sex)})
  })
}
// 头部新增按钮点击事件
const handleAdd = () => {
  dialogVisible.value = true
  action.value = 'add'
}
// 对话框右上角的关闭事件
const handleBeforeClose = () => {
  // 重置表单
  dialogVisible.value = false
  proxy.$refs['userForm'].resetFields()
}
// 对话框右下角的取消事件
const handleCancel = () => {
  dialogVisible.value= false
  proxy.$refs['userForm'].resetFields()
}
// 时间格式化函数，格式化为：1997-01-02这种格式
const timeFormat = (t) => {
  const time = new Date(t)
  const year = time.getFullYear()
  const month = time.getMonth()+1
  const day = time.getDate()
  function add(t) {
    return t < 10 ? '0' + t : t
  }
  return `${year}-${add(month)}-${add(day)}`
}
// 对话框右下角的确认提交事件
const onSubmit = () => {
  // 先校验，执行userForm表单的validate进行规则校验，传入一个回调函数，回调函数会接受到一个是否校验通过的变量
  proxy.$refs['userForm'].validate(async (valid) => {
    // 如果校验成功
    if (valid) {
      // res用于接收添加用户或者编辑用户接口的返回值
      let res = null
      // 这里无论是新增或者是编辑，都要对这个日期进行一个格式化
      formUser.birth = /^\d{4}-\d{2}-\d{2}/.test(formUser.birth) ? formUser.birth : timeFormat(formUser.birth)
      // 如果当前的操作是新增，则调用新增接口
      if (action.value === 'add') {
        res = await proxy.$api.addUser(formUser)
      } else if (action.value === 'edit') {
        // 如果当前的操作是编辑，则调用编辑接口
        res = await proxy.$api.editUser(formUser)
      }

      // 如果接口调用成功
      if (res) {
        // 关闭对话框，重置表单，刷新表格数据
        dialogVisible.value = false
        proxy.$refs['userForm'].resetFields()
        getUserData()
      }
    } else {
      // 如果校验失败
      ElMessage.error({
        message: '校验未通过',
        showClose: true
      })
      return
    }
  })
}

onMounted(() => {
  getUserData()
})
</script>

<template>
  <!-- 头部 -->
  <div class="user-header">
    <el-button type="primary" icon="plus" @click="handleAdd">新增</el-button>
    <el-form :model="formInline" inline>
      <el-form-item>
        <el-input @keyup.enter="handleSearch" v-model.trim="formInline.keyword" placeholder="请输入用户名"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button @click="handleSearch" type="primary">搜索</el-button>
      </el-form-item>
    </el-form>
  </div>

  <!-- 表格 -->
  <div class="table">
    <el-table :data="tableData" style="width: 100%">
      <el-table-column
        v-for="item in tableLabel"
        :key="item.prop"
        :width="item.width ? item.width : 125"
        :prop="item.prop"
        :label="item.label"
      />
      <el-table-column fixed="right" label="操作" min-width="120">
        <template #default="{ row }">
          <el-button type="primary" size="small" @click="handleEdit(row)">
            编辑
          </el-button>
          <el-button type="danger" size="small" @click="handleDelete(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      background
      layout="prev, pager, next"
      :total="config.total"
      size="small"
      @current-change="handleChange"
      class="pager"
      hide-on-single-page
    />
  </div>

  <!-- 新增对话框 -->
  <el-dialog
    v-model="dialogVisible"
    :title="action === 'add' ? '新增用户' : '编辑用户'"
    width="40%"
    :before-close="handleBeforeClose"
  >
    <!-- 需要注意的是设置了inline="true"，会对el-select的样式造成影响，通过给css处理 -->
    <el-form
      inline
      :model="formUser"
      :rules="rules"
      ref="userForm"
    >
      <el-row>
        <el-col :span="12">
          <el-form-item label="姓名" prop="name">
            <el-input v-model.trim="formUser.name" placeholder="请输入姓名" clearable />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="年龄" prop="age">
            <el-input v-model.number="formUser.age" placeholder="请输入年龄" clearable />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="性别" prop="sex">
            <el-select v-model="formUser.sex" placeholder="请选择">
              <el-option label="男" value="1" />
              <el-option label="女" value="0" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="出生日期" prop="birth">
            <el-date-picker
              v-model="formUser.birth"
              type="date"
              placeholder="请输入"
              style="width: 100%;"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item style="width: 90%;" label="地址" prop="addr">
            <el-input v-model.trim="formUser.addr" placeholder="请输入地址" clearable />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row style="justify-content: flex-end;">
        <el-form-item style="width: auto;">
          <el-button @click="handleCancel">取消</el-button>
          <el-button type="primary" @click="onSubmit">确认</el-button>
        </el-form-item>
      </el-row>
    </el-form>
  </el-dialog>
  
</template>

<style lang="less" scoped>
.user-header {
  display: flex;
  justify-content: space-between;
}
.table {
  position: relative;
  height: 520px;
  .pager {
    position: absolute;
    right: 10px;
    bottom: 30px;
  }
  .el-table {
    width: 100%;
    height: 500px;
  }
}

.el-dialog {
  .el-form-item {
    width: 80%;
  }
}
</style>